import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { switchMap } from 'rxjs/operators';
import { Hero } from './hero';
import { HeroesService } from './heroes.service';


@Component({
  template: `
    <h2>HEROES</h2>
    <p>get your heroes here</p>
    <ul class="items">
      <li *ngFor="let hero of hero$ | async"
        [class.selected]="hero.id === selectedId">
        <a [routerLink]="['/hero', hero.id]">
          <span class="badge">{{ hero.id }}</span>{{ hero.name }}
        </a>
      </li>
    </ul>
    <button routerLink="/sidekicks">go to sidekicks</button>
  `
})
export class HeroListComponent implements OnInit {

  hero$: Observable<Hero[]>;

  private selectedId: number;

  constructor(
    private service: HeroesService,
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.hero$ = this.route.paramMap.pipe(
      switchMap((params: ParamMap) => {
        // (+) before `params.get()` turns the string into a number
        this.selectedId = +params.get('id');
        return this.service.getHeroes();
      })
    );
  }
}
